package fudan.se.project.security.filter;

import fudan.se.project.domain.User;
import fudan.se.project.service.infrastructure.entity.UserService;
import fudan.se.project.util.jwt.JwtTokenUtil;
import io.jsonwebtoken.MalformedJwtException;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

/**
 * Write your code to make this filter works.
 *
 * @author LBW
 */

@Slf4j
@Component
public class JwtRequestFilter extends OncePerRequestFilter {

    private static final String AUTH_HEADER_NAME = "Authorization";
    private static final String TOKEN_HEAD = "Bearer";


    private final JwtTokenUtil jwtTokenUtil;
    private final UserService userService;


    @Autowired
    public JwtRequestFilter(JwtTokenUtil jwtTokenUtil, UserService userService) {
        this.jwtTokenUtil = jwtTokenUtil;
        this.userService = userService;
    }

    /**
     * Authenticates user by the token in http header 'Authorization'.
     */
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
            FilterChain filterChain) throws ServletException, IOException {

        String authHeader = request.getHeader(AUTH_HEADER_NAME);
        String token = null;

        String username = null;
        User user = null;

        if (authHeader != null && authHeader.startsWith(TOKEN_HEAD)) {
            token = authHeader.substring(TOKEN_HEAD.length() + 1);
            try {
                username = jwtTokenUtil.getUsernameFromToken(token);
            } catch (MalformedJwtException ex) {
                log.warn("malformed jwt: " + token);
            } catch (Exception ex) {
                log.error("unexpected error: jwt = " + token);
            }
        }

        if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {

            user = userService.findByUsername(username);
        }

        if (user != null) {
            boolean checkResult = false;
            try {
                checkResult = jwtTokenUtil.validateToken(token, user);
            } catch (Exception ex) {
                log.warn("invalid token: " + token);
            }
            if (checkResult) {
                UsernamePasswordAuthenticationToken authToken =
                        new UsernamePasswordAuthenticationToken(user, null,
                                user.getAuthorities());
                authToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));

                SecurityContextHolder.getContext().setAuthentication(authToken);
            }
        }

        filterChain.doFilter(request, response);
    }
}
